﻿using AduSkin.Controls.Metro;
using DBMC_Core;
using Microsoft.Win32;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Windows;

namespace DBMC
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        Init init = new Init();
        public ObservableCollection<UserInfo> Users { get; set; }
        LauncherCore launcherCore = new LauncherCore();
        MainWindow DBMC_Main = new MainWindow();
        RootObject dbmcData;
        private bool showMainWindow = true;

        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            SetupCustomProtocolHandler();
            LauncherCore.WriteLog("启动器核心：消息通知插件已加载");
            NoticeManager.Initialize();
            // 检查启动参数
            if (e.Args.Length > 0)
            {
                ProcessStartupArguments(e.Args);
            }
            // 根据标志决定是否显示MainWindow
            if (showMainWindow)
            {
                if (!launcherCore.ConfigFileExists)
                {
                    //LauncherCore.WriteLog("启动器核心：首次启动或未找到配置文件，进入初始化");
                    init.Show();
                    return;
                }
                DBMC_Main.Show();
            }
        }
        protected override void OnExit(ExitEventArgs e)
        {
            base.OnExit(e);
            NoticeManager.ExitNotification();
            LauncherCore.WriteLog("启动器核心：消息通知插件已卸载");
        }

        //[DllImport("User32.dll")]
        //private static extern bool SetForegroundWindow(IntPtr handle);
        //[DllImport("User32.dll")]
        //private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        //private const string UniqueEventName = "DBMC";
        //private const string MainWindowTitle = "主播蛋白造图端";
        //private EventWaitHandle eventWaitHandle;

        //private void RegisterEventWaitHandle()
        //{
        //    ThreadPool.RegisterWaitForSingleObject(eventWaitHandle, WaitOrTimerCallback, null, Timeout.Infinite, false);
        //}

        //private void WaitOrTimerCallback(object state, bool timedOut)
        //{
        //    Current.Dispatcher.Invoke(() =>
        //    {
        //        ActivateExistingWindow();
        //    });
        //}
        //private void ActivateExistingWindow()
        //{
        //    var otherWindowHandle = FindWindow(null, MainWindowTitle);
        //    if (otherWindowHandle != IntPtr.Zero)
        //    {
        //        // 将已经打开的窗口调至最前
        //        SetForegroundWindow(otherWindowHandle);
        //    }
        //}
        private void SetupCustomProtocolHandler()
        {
            // Dbmc protocol key path
            const string protocolKeyPath = @"Software\Classes\dbmc";

            // Check if our protocol is already registered
            RegistryKey protocolKey = Registry.CurrentUser.OpenSubKey(protocolKeyPath);
            if (protocolKey == null)
            {
                LauncherCore.WriteLog("启动器核心：注册 dbmc协议");
                // Protocol is not registered, so create new key
                protocolKey = Registry.CurrentUser.CreateSubKey(protocolKeyPath);
                if (protocolKey != null)
                {
                    protocolKey.SetValue(string.Empty, "URL:Dbmc Protocol");
                    protocolKey.SetValue("URL Protocol", string.Empty);

                    // Use a method to get the dynamic path to the application
                    string applicationPath = GetDynamicApplicationPath();

                    RegistryKey shellKey = protocolKey.CreateSubKey(@"shell\open\command");
                    // Use the dynamically obtained path
                    shellKey.SetValue(string.Empty, $"\"{applicationPath}\" \"%1\"");
                    LauncherCore.WriteLog("启动器核心：刷新 dbmc协议");
                }
            }
        }

        private string GetDynamicApplicationPath()
        {
            // This is where you'd implement logic to retrieve the updated application path.
            // For now, we're just defaulting to the current executing assembly's location.
            return System.Reflection.Assembly.GetExecutingAssembly().Location;
        }
        private void ProcessStartupArguments(string[] args)
        {
            foreach (string arg in args)
            {
                if (arg.StartsWith("dbmc://startgame/"))
                {
                    LauncherCore.WriteLog("启动器核心：dbmc协议 - 用户调用“快捷启动游戏”");
                    showMainWindow = false;
                    if (launcherCore.ConfigFileExists)
                    {
                        string jsonData = File.ReadAllText(launcherCore.ConfigFile);
                        dbmcData = JsonConvert.DeserializeObject<RootObject>(jsonData);
                        if (dbmcData?.Account == null)
                        {
                            LauncherCore.WriteLog("启动器核心：dbmc协议 - 快捷启动游戏失败，未找到账号");
                            MessageBox.Show("还没添加游戏账号，请添加或选择账号后再次启动");
                            DBMC_Main.Show();
                            return;
                        }
                        else
                        {
                            Users = new ObservableCollection<UserInfo>(dbmcData.Account);
                            List<UserInfo> selectedUsers = Users.Where(u => u.IsSelected).ToList();
                            if (selectedUsers.Count <= 0)
                            {
                                LauncherCore.WriteLog("启动器核心：dbmc协议 - 快捷启动游戏失败，未启用账号");
                                AduMessageBox.Show("还没选择游戏账号，请添加或选择账号后再次启动");
                                DBMC_Main.Show();
                                return;
                            }
                            else
                            {
                               LauncherCore.WriteLog("启动器核心：dbmc协议 - 快捷启动游戏成功");
                                DBMC_Main.StartGame();
                            }
                        }
                    }
                }
            }
        }
    }
}